import { t } from 'i18next'
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { Mt } from '@/api/manager/mt'
import {
	CameraPosInfoData,
	IMonitorFailData,
	ISelectItem,
	actionRepeatOrder,
	getPositionList,
	getVideoSourceList,
	isSameList,
} from './interface'
import { useMccStore } from '../../store'
import {
	fetchChangePosition,
	fetchGetCurVideoSource,
	fetchGetPosition,
	fetchGetVideoSource,
	fetchSavePosition,
	fetchSetVideoSource,
	fetchStartMove,
	fetchStopMove,
} from '@/api/manager/cameraRc'
import Alert from '@/components/Alert'
import { IVideoSourceListItem } from '@/api/manager/cameraRc/interface'
import { store as msgStore } from '@/pages/manager/blocks/helper/store'
import { useTableAllStore } from '../main/table/all/store'
import { getItemByMtKey } from '../main/table/all/utils'
import { useMonitorStore } from '../monitor/store'
type StateStore = {
	mt: Mt | null
	mt_id: string
	sourceList: ISelectItem[]
	curSource: string
	positionList: ISelectItem[]
	curPosition: string
	choosePosition: string
	isOverrideDialogShow: boolean
	isChooseDialogShow: boolean
	/** 眼睛图标是否active状态 */
	isToggleIconActive: boolean
	_timer: NodeJS.Timer | null
	_preData: CameraPosInfoData | null //用于对比推送来的列表是否相同
}
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	fetchGetVideoSourceList: () => Promise<void>
	fetchCurVideoSource: () => Promise<void>
	renderVideoSourceList: (list: IVideoSourceListItem[] | undefined) => void
	setVideoSource: (val: string) => Promise<void>
	fetchGetPosition: () => Promise<void>
	changePosition: (id: string, name: string) => Promise<void>
	savePosition: (val: string) => Promise<void>
	actionRepeat: (action: string, method: 'start' | 'stop') => void
	fetchStartMove: (action: string) => Promise<void>
	fetchStopMove: (action: string) => Promise<void>
	notifyFail: (data: IMonitorFailData) => void
	notifyParse: (data: CameraPosInfoData | undefined) => void
}
const initialState: StateStore = {
	mt: null,
	mt_id: '',
	sourceList: [],
	curSource: '-1',
	positionList: [],
	curPosition: '-1',
	choosePosition: '-1',
	isOverrideDialogShow: false,
	isChooseDialogShow: false,
	isToggleIconActive: false,
	_timer: null,
	_preData: null,
}
export const useCameraRcStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		fetchGetVideoSourceList: async () => {
			const { mt_id, renderVideoSourceList } = get()
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			let res = await fetchGetVideoSource(meetingMoid, mt_id)
			if (res.success) {
				renderVideoSourceList(res.data)
			} else {
				Alert(t('获取终端视频源失败'))
			}
		},
		renderVideoSourceList: (list) => {
			const { update, fetchCurVideoSource } = get()
			let _list = []
			if (list) {
				_list = list.map((item) => ({ label: item.vid_alias, value: item.vid_port_idx }))
				_list.unshift({ label: t('请选择'), value: '-1' })
				update({ sourceList: _list })
				fetchCurVideoSource()
			} else {
				_list = getVideoSourceList()
				update({ sourceList: _list })
			}
		},
		fetchCurVideoSource: async () => {
			const { mt_id, update } = get()
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			let res = await fetchGetCurVideoSource(meetingMoid, mt_id)
			if (res.success && res.data) {
				update({ curSource: res.data.cur_video_src_idx })
			} else {
				Alert(t('获取当前终端视频源失败'))
			}
		},
		setVideoSource: async (val) => {
			const { mt_id, update } = get()
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			if (val === '-1') {
				update({ curSource: val })
				return
			}
			let data = await fetchSetVideoSource(meetingMoid, mt_id, val)
			if (!data) {
				Alert(t('设置终端视频源失败'))
			} else {
				update({ curSource: val })
			}
		},
		fetchGetPosition: async () => {
			const { mt_id, update } = get()
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			update({ positionList: getPositionList() })
			let res = await fetchGetPosition(meetingMoid, mt_id)
			if (!res.success) {
				Alert(t('获取终端预置位失败'))
			}
		},
		changePosition: async (val, name) => {
			const { mt_id, update } = get()
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			if (val === '-1' || val.indexOf('_unUsed') !== -1) {
				update({ curPosition: val })
				return
			}
			let res = await fetchChangePosition(meetingMoid, mt_id, val, name)
			if (res.success) {
				update({ curPosition: val })
			} else {
				Alert(t('调用终端预置位失败'))
			}
		},
		savePosition: async (val) => {
			const { mt_id, fetchGetPosition } = get()
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			let res = await fetchSavePosition(meetingMoid, mt_id, val)
			if (res.success) {
				fetchGetPosition()
			} else {
				Alert(t('保存终端预置位失败'))
			}
		},
		actionRepeat: (action, method) => {
			const { _timer, update, fetchStartMove, fetchStopMove } = get()
			const requestAction = actionRepeatOrder[action]
			if (!requestAction) return
			if (method === 'start') {
				if (_timer) {
					clearInterval(_timer)
					update({ _timer: null })
				}
				fetchStartMove(requestAction)
				let timer = setInterval(() => {
					fetchStartMove(requestAction)
				}, 250)
				update({ _timer: timer })
			} else if (method === 'stop') {
				if (_timer) {
					clearInterval(_timer)
					update({ _timer: null })
					fetchStopMove(requestAction)
				}
			}
		},
		fetchStartMove: async (action) => {
			const { mt_id } = get()
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			let res = await fetchStartMove(meetingMoid, { mt_id, action })
			if (!res.success) {
				console.log('操作失败')
			}
		},
		fetchStopMove: async (action) => {
			const { mt_id } = get()
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			let res = await fetchStopMove(meetingMoid, { mt_id, action })
			if (!res.success) {
				console.log('操作失败')
			}
		},
		notifyParse: (data) => {
			if (!data) return
			if (useMccStore.getState().curPage !== 'mt_camera') {
				return
			}
			const { mt_id, _preData, update } = get()
			let _mt_id = data.mt.mcu_idx ? `${data.mt.mcu_idx}_${data.mt.mt_id}` : data.mt.mt_id
			if (_mt_id !== mt_id) {
				//判断是不是当前mt的预置位信息
				// console.log(t('会管收到的终端上报的预置位信息是过时信息（不是当前终端的），废弃。'))
				return
			}
			if (_preData && isSameList(data, _preData)) {
				//判断终端返回的消息与页面中的缓存是否一致，一致则不重新渲染预置位下拉列表
				// console.log(t('会管收到的终端上报的预置位信息与页面缓存信息一致，废弃。'))
				return
			}
			let _positionList: ISelectItem[] = [{ label: t('请选择'), value: '-1' }]
			data.channels[0].pos_info.forEach((item) => {
				if (item.name) {
					_positionList.push({ label: item.name, value: item.pos })
				} else {
					_positionList.push({ label: t('(空)'), value: item.pos + '_unUsed' })
				}
			})
			update({ _preData: data, positionList: _positionList })
		},
		notifyFail: (data) => {
			//开启监控失败
			// console.log(t('Monitor 收到错误消息。。'))
			let errCode = data.err_code
			//端口资源不足要调exe的停止
			if (
				((Number(errCode) >= 29301 && Number(errCode) <= 29461) || errCode == '21751') &&
				data['dst_addr'] !== undefined &&
				data.dst_addr.length > 0
			) {
				let param = {
					event: 'KCMP_STOP_PLAY_CMD',
					dst: data.dst_addr.map((item) => ({
						ip: item.ip,
						port: parseInt(item.port),
					})),
				}
				useMonitorStore.getState().webToNativeEntry('StopMonitor', param)
			}
			if (errCode == '20512') {
				let tree = useTableAllStore.getState().tree
				let item = getItemByMtKey(tree, data.mt_id)?.mcc as Mt
				msgStore.getState().msgHandle({
					type: 'err_mcu_audiomtnomonitorsrc',
					operation_user: {
						name: item?.name ?? '',
						account: item?.account ?? '',
						account_type: item?.accountType ?? 5,
						mt_id: item?.mtKey ?? '',
						mt_key: item?.mtKey ?? '',
						conf_e164: item?.confE164 ?? '',
						protocol: item?.protocol ?? 0,
					},
				})
				return
			} else if (errCode == '20513') {
				msgStore.getState().msgHandle({
					type: 'err_mcu_mtnovidsrc',
				})
				return
			} else if (errCode == '21741') {
				msgStore.getState().msgHandle({
					type: 'err_mcu_casdbasisnotenough',
					_isMonitorPopup: true,
				})
				return
			} else if (errCode == '21744') {
				msgStore.getState().msgHandle({
					type: 'err_mcu_spymtstate_waitfree',
				})
				return
			} else if (Number(errCode) >= 29301 && Number(errCode) <= 29461) {
				msgStore.getState().msgHandle({
					type: '',
					error_code: Number(errCode),
					_isMonitorPopup: true,
				})
				//给到监控exe消息
				return
			} else if (errCode == '21751') {
				msgStore.getState().msgHandle({
					type: 'err_mcu_mediaresnotenough',
					_isMonitorPopup: true,
				})
				//给到监控exe消息
				return
			}
			// } else {
			// 	msgStore.getState().msgHandle({
			// 		type: 'err_mcu_spymtstate_unknownerror', //该类型被注释，不知道要不要
			// 		error_code: errCode,
			// 	})
			// 	return
			// }
		},
	}))
)
